<template>
  <van-popup
    v-model:show="visible"
    :closeable="false"
    position="bottom"
    @close="handleClose"
  >
    <van-cascader
      v-model="cascaderValue"
      title="请选择所在地区"
      :options="options"
      :field-names="{
        text: 'name',
        value: 'name',
      }"
      @close="handleClose"
      @finish="onFinish"
    />
  </van-popup>
</template>

<script lang="ts" setup>
  import { ref, withDefaults, defineProps } from 'vue';
  import { apiGetDepartmentList } from '@/api/system';

  interface Props {
    value: string;
    close: () => void;
    resolve: (x?: any) => void;
  }
  const props = withDefaults(defineProps<Props>(), {
    close: () => {
      return () => {};
    },
    resolve: () => {
      return () => {};
    },
  });

  let type = '';
  const loading = ref<boolean>(false);
  const visible = ref<boolean>(true);

  const options = ref([]);
  const cascaderValue = ref('');

  const getTree = (list: any) => {
    const arr = list.map((t) => {
      const item = {
        ...t,
      };
      if (item?.child?.length) {
        item.children = getTree(item.child);
      }
      delete item.child;
      return item;
    });

    return arr;
  };

  const getOptions = () => {
    apiGetDepartmentList().then((res) => {
      options.value = getTree(res.data);
    });
  };
  const getDetail = () => {
    if (props.value) {
      const arr = props.value.split('/');
      cascaderValue.value = arr[arr.length - 1];
    }
  };

  getDetail();
  getOptions();

  let result = '';
  const onFinish = ({ selectedOptions }: any) => {
    result = selectedOptions.map((option: any) => option.name).join('/');
    handleSuccess();
  };

  const handleSuccess = () => {
    type = 'reslove';
    visible.value = false;
  };

  const handleClose = () => {
    loading.value = false;
    if (type === 'reslove') {
      props.resolve(result);
    } else {
      props.close();
    }
  };
</script>

<style lang="less"></style>
